import {
  Body,
  Controller,
  Get,
  Post,
  Res,
  UploadedFile,
  UseInterceptors,
} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { ToolsService } from 'common/lib/utils/tools.service';
import { ExcelService } from '../service/excel.service';
import { join } from 'path';
import urlencode from 'urlencode';

@Controller('excel')
export class ExcelController {
  constructor(private readonly excelService: ExcelService) {}

  //文件上传
  @Post('import')
  @UseInterceptors(FileInterceptor('file')) //获取header的file文件
  //从UploadedFile可获取
  async analyze(@UploadedFile() file, @Body() body) {
    try {
      //图片命名空间
      const namespace = body.namespace
        ? body.namespace.replace(/\s+/g, '')
        : '';
      const workbook = await this.excelService.readExcel(file.buffer);
      const worksheet = workbook.worksheets[0];
      const rows = [];
      worksheet.eachRow((row) => {
        const rowData = [];
        row.eachCell((cell) => {
          rowData.push(cell.value);
        });
        rows.push(rowData);
      });
      console.log('.........', JSON.stringify(rows));
      // 下面自己进行逻辑处理，也可以为了防止报错，使用try...catch...

      return JSON.stringify(rows);
    } catch (error) {
      ToolsService.fail(error);
    }
  }

  @Get('export')
  async readWriteExcel(@Res() res) {
    const templatePath = join(
      __dirname,
      '../../uploads',
      '导入模板-法人公司默认配置表.xlsx',
    ); // 指定文件路径

    let stream = await this.excelService.readWriteExcel(templatePath);

    let name = urlencode('法人公司默认配置表' + '.xlsx', 'utf-8');
    // 设置响应头
    res.setHeader(
      'Content-Type',
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    );
    res.setHeader(
      'Content-Disposition',
      "attachment; filename* = UTF-8''" + name,
    );
    res.send(stream);
  }
}
